"""
简化日志服务 - 基本日志功能
"""

import logging
import os
import streamlit as st
from datetime import datetime
from pathlib import Path
from typing import Dict, Any, Optional


class LoggerService:
    """简化日志服务类"""
    
    def __init__(self):
        """初始化日志服务"""
        self.log_dir = Path("logs")
        self.log_dir.mkdir(exist_ok=True)
        
        # 日志文件
        self.system_log_file = self.log_dir / "system.log"
        self.error_log_file = self.log_dir / "error.log"
        
        # 配置应用日志
        self.app_logger = self._setup_logger()
    
    def _setup_logger(self) -> logging.Logger:
        """设置日志器"""
        logger = logging.getLogger("vector_service")
        
        # 避免重复设置
        if logger.handlers:
            return logger
        
        logger.setLevel(logging.INFO)
        
        # 控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        console_formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        )
        console_handler.setFormatter(console_formatter)
        logger.addHandler(console_handler)
        
        # 文件处理器
        try:
            file_handler = logging.FileHandler(
                str(self.system_log_file),
                encoding='utf-8'
            )
            file_handler.setLevel(logging.INFO)
            file_formatter = logging.Formatter(
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
            )
            file_handler.setFormatter(file_formatter)
            logger.addHandler(file_handler)
        except Exception as e:
            print(f"文件日志处理器初始化失败: {e}")
        
        return logger
    
    def log_system_event(self, event_type: str, message: str, 
                        details: Dict[str, Any] = None, level: str = "info"):
        """
        记录系统事件
        
        Args:
            event_type: 事件类型
            message: 日志消息
            details: 额外详情
            level: 日志级别 (info, warning, error, debug)
        """
        try:
            # 构建完整消息
            full_message = f"[{event_type}] {message}"
            if details:
                full_message += f" | Details: {details}"
            
            # 根据级别记录日志
            if level.lower() == "debug":
                self.app_logger.debug(full_message)
            elif level.lower() == "warning":
                self.app_logger.warning(full_message)
            elif level.lower() == "error":
                self.app_logger.error(full_message)
            else:
                self.app_logger.info(full_message)
                
        except Exception as e:
            # 如果日志记录失败，至少打印到控制台
            print(f"日志记录失败: {e} | 原消息: {message}")
    
    def log_info(self, message: str):
        """记录信息日志"""
        self.log_system_event("INFO", message, level="info")
    
    def log_warning(self, message: str):
        """记录警告日志"""
        self.log_system_event("WARNING", message, level="warning")
    
    def log_error(self, message: str, error: Exception = None):
        """记录错误日志"""
        details = {"error": str(error)} if error else None
        self.log_system_event("ERROR", message, details, level="error")
    
    def log_debug(self, message: str):
        """记录调试日志"""
        self.log_system_event("DEBUG", message, level="debug")


# 全局日志服务实例
@st.cache_resource
def get_logger_service() -> LoggerService:
    """
    获取日志服务实例 (带缓存)
    
    Returns:
        LoggerService: 日志服务实例
    """
    return LoggerService()